from django.views import View
from .models import  User
from django import http
import json
import re
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout


class EmailView(View):

    def put(self,request):
        """修改email接口"""
        # 1.json格式接收参数email
        dict = json.loads(request.body)
        email=dict.get('email')
        # 2.检查email是否存在
        if not email:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '缺少email参数'
            })
        # 3.检查email格式是否正确
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return http.JsonResponse({
                'code': 400,
                'errmsg': 'email格式错误'
            })
        # 4.保存到数据库
        try:
            # update方法
            # User.objects.filter(username=request.user.username).update(email=email)
            request.user.email =email
            request.user.save()
        except Exception as e:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '修改数据库失败'
            })
        # 5.返回json
        return http.JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })






class UserInfoView(View):

    def get(self,request):
        """返回用户中心数据接口"""
        # 1.拼接字典参数
        dict ={
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active
        }
        # 2.返回json
        return http.JsonResponse({
            'code':0,
            'errmsg':'ok',
            'info_data':dict
        })



class LogoutView(View):
    # 退出登录接口
    def delete(self,request):
        # 1.删除session
        logout(request)
        # 2.清除cookie
        response =http.JsonResponse({
            'code':'0',
            'errmsg':'ok'
        })
        response.delete_cookie('username')
        # 3.返回
        return response




class loginView(View):
    # 登录接口
    def post(self,request):
        # 1.接收用户的参数
        dict = json.loads(request.body)
        username =dict.get('username')
        password =dict.get('password')
        remembered = dict.get('remebered')
        # 2.进行总体检验
        if not all([username,password]):
            return http.JsonResponse({
                'code':'400',
                'errmsg':'缺少必填参数'
            })
        # 3.用户名正则检username(因为username包含用户名和手机号，所以这个只能验证用户名的正则有问题，需要删掉）
        # 4.密码正则检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({
                'code': '400',
                'errmsg': 'password格式错误'
            })
        # 5.检验用户能否登录（去数据库中取出数据和用户输入的进行比对）
        # authenticate这个函数只认用户名不认手机号，所以需要重写这个函数
        user = authenticate(username=username,password=password)
        if user is None:
            return http.JsonResponse({
                'code': '400',
                'errmsg': '用户名或密码错误'
            })
        # 6.状态保持
        login(request,user)
        # 7.判断用户是否记住登录
        if remembered != True:
            # 关闭浏览器即失效
            request.session.set_expiry(0)
        else:
            # 如果记住，设置默认时间为两周
            request.session.set_expiry(None)
        # 返回
        response=http.JsonResponse({
            'code':'0',
            'errmsg':'ok'
        })
        response.set_cookie('username',user.username,max_age=3600*24*14)
        return response






class RegisterView(View):
    # 注册接口
    def post(self,request):
        # 1.接收前端传入参数
        dict = json.loads(request.body)
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        allow = dict.get('allow')
        sms_code_client = dict.get('sms_code')
        # 2.进行总体检验
        if not all([username,password,password2,mobile,allow,sms_code_client]):
            return http.JsonResponse({
                'code':'400',
                'errmsg':'缺少必传参数'
            })
        # 3.用户名正则检username
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.JsonResponse({
                'code':'400',
                'errmsg':'username格式错误'
            })
        # 4.密码正则检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
            return http.JsonResponse({
                'code':'400',
                'errmsg':'password格式错误'
            })
        # 5.密码和确认密码的检验
        if password != password2:
            return http.JsonResponse({
                'code':'400',
                'errmsg':'两次输入不一致'
            })
        # 6.手机号码的检验
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({
                'code':'400',
                'errmsg':'mobile格式错误'
            })
        # 7.是否同意用户协议的检验
        if allow !=True:
            return http.JsonResponse({
                'code':'400',
                'errmsg':'allow格式错误'
            })
        # 8.链接redis,获取redis对象
        redis_coon =get_redis_connection('verify_code')
        # 9.取出redis中短信的信息
        sms_code_server = redis_coon.get('sms_%s'%mobile)
        # 10.验证redis中的短信验证码是否存在
        if sms_code_server is None:
            return http.JsonResponse({
                'code':'400',
                'errmsg':'短信验证码过期'
            })
        # 11.将redis中取出的数据和前端发送的数据进行比对
        if sms_code_client !=sms_code_server.decode():
            return http.JsonResponse({
                'code':'400',
                'errmsg':'验证码错误'
            })
        # 12.保存到数据库中
        try:
            user = User.objects.create_user(username=username,password=password,mobile =mobile)
        except Exception as e:
            return http.JsonResponse({
                'code': '400',
                'errmsg': '保存到数据库出错'
            })
        # 13.保持登录状态
        login(request,user)
        # 13.返回信息
        response =http.JsonResponse({
                'code': '0',
                'errmsg': 'ok'
            })
        response.set_cookie('username',user.username,max_age=3600*24*12)
        return response



class UsernameCountView(View):
    # 处理用户名重复问题
    def get(self,request,username):
        try:
            # 1.数据库查询
            count=User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({
                'code':'400',
                'errmsg':'数据库查询失败'
            })
        # 返回数据
        return http.JsonResponse({
            'code':'0',
            'errmsg':'ok',
            'count':count,
        })


class UsermobileCountView(View):
    # 处理用户手机号重复问题
    def get(self,request,mobile):
        try:
            # 1.查询数据库
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({
                'code':'400',
                'errmsg':'数据库查询失败'
            })
        return http.JsonResponse({
            'code':'0',
            'errmsg':'ok',
            'count':count,
        })